package com.jpro.module.system.service.auth;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.annotations.VisibleForTesting;
import com.jpro.framework.common.enums.CommonStatusEnum;
import com.jpro.framework.common.enums.UserTypeEnum;
import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.framework.common.util.monitor.TracerUtils;
import com.jpro.framework.common.util.servlet.ServletUtils;
import com.jpro.framework.common.util.validation.ValidationUtils;
import com.jpro.framework.security.core.util.RequestUtils;
import com.jpro.framework.web.config.WebProperties;
import com.jpro.module.system.api.logger.dto.LoginLogCreateReqDTO;
import com.jpro.module.system.api.sms.SmsCodeApi;
import com.jpro.module.system.api.social.dto.SocialUserBindReqDTO;
import com.jpro.module.system.api.social.dto.SocialUserRespDTO;
import com.jpro.module.system.api.user.vo.MemberAuthLoginRespVO;
import com.jpro.module.system.api.user.vo.MemberUserRespVo;
import com.jpro.module.system.api.user.vo.SimpleAuthLoginReqVO;
import com.jpro.module.system.api.user.vo.UserLockReqVO;
import com.jpro.module.system.cache.CacheService;
import com.jpro.module.system.config.JproProperties;
import com.jpro.module.system.controller.admin.auth.vo.*;
import com.jpro.module.system.convert.auth.AuthConvert;
import com.jpro.module.system.convert.user.MemberUserConvert;
import com.jpro.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import com.jpro.module.system.dal.dataobject.user.AdminUserDO;
import com.jpro.module.system.enums.common.EnumIntCommonStatus;
import com.jpro.module.system.enums.logger.LoginLogTypeEnum;
import com.jpro.module.system.enums.logger.LoginResultEnum;
import com.jpro.module.system.enums.oauth2.OAuth2ClientConstants;
import com.jpro.module.system.enums.sms.SmsSceneEnum;
import com.jpro.module.system.job.SystemJobService;
import com.jpro.module.system.service.dept.DeptService;
import com.jpro.module.system.service.logger.LoginLogService;
import com.jpro.module.system.service.member.MemberService;
import com.jpro.module.system.service.oauth2.OAuth2TokenService;
import com.jpro.module.system.service.social.SocialUserService;
import com.jpro.module.system.service.user.AdminUserService;
import com.jpro.module.system.util.SM2Util;
import com.jprocms.module.cms.api.GlobalConfigApi;
import com.jprocms.module.cms.api.dto.AdminIpConfig;
import com.jprocms.module.cms.api.dto.GlobalConfigRespVO;
import com.jprocms.module.cms.api.dto.IpRangeVO;
import com.jprocms.module.cms.api.dto.SecurityConfig;
import com.xingyuv.captcha.model.common.ResponseModel;
import com.xingyuv.captcha.model.vo.CaptchaVO;
import com.xingyuv.captcha.service.CaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.jpro.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jpro.framework.common.util.servlet.ServletUtils.getClientIP;
import static com.jpro.module.system.config.ThreadPoolConfiguration.SYSTEM_COMMON_THREAD_POOL_TASK_EXECUTOR;
import static com.jpro.module.system.dal.redis.RedisKeyConstants.*;
import static com.jpro.module.system.enums.ErrorCodeConstants.*;

/**
 * Auth Service 实现类
 *
 * @author JPROCMS
 */
@Service
@Slf4j
public class AdminAuthServiceImpl implements AdminAuthService {

    @Resource
    private AdminUserService userService;
    @Resource
    private LoginLogService loginLogService;
    @Resource
    private OAuth2TokenService oauth2TokenService;
    @Resource
    private SocialUserService socialUserService;
    @Resource
    private MemberService memberService;
    @Resource
    private Validator validator;
    @Resource
    private CaptchaService captchaService;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private SystemJobService jobService;

    /**
     * 验证码的开关，默认为 true
     */
    @Value("${jpro.captcha.enable:true}")
    private Boolean captchaEnable;
    @Resource
    private JproProperties jproProperties;
    @Resource
    private DeptService deptService;
    private WebProperties webProperties;
    @Resource
    private CacheService cacheService;
    @Resource
    private GlobalConfigApi globalConfigApi;
    @Resource(name = SYSTEM_COMMON_THREAD_POOL_TASK_EXECUTOR)
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public AdminAuthServiceImpl(WebProperties webProperties) {
        this.webProperties = webProperties;
    }

    @Override
    public AdminUserDO authenticate(String username, String password) {
        final CommonResult<GlobalConfigRespVO> globalConfigResp = globalConfigApi.getGlobalConfig();
        SecurityConfig securityConfig = new SecurityConfig();
        AdminIpConfig adminIpConfig = new AdminIpConfig();
        if (globalConfigResp.isSuccess()) {
            securityConfig = globalConfigResp.getData().getSecurityConfig();
            adminIpConfig = globalConfigResp.getData().getAdminIpConfig();
        }
        //验证ip是否禁用
        checkIpForbidden(securityConfig);
        //检查ip是否在ip白名单内
        final String clientIP = getClientIP();
        if (!ipIsAllowd(clientIP, adminIpConfig)) {
            log.info("ip不在允许的ip白名单内，访问被禁止 {}", clientIP);
            throw exception(AUTH_LOGIN_IP_NOT_IN_WHITELIST);
        }
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
        // 校验账号是否存在
        AdminUserDO user = userService.getUserByUsername(username);
        if (user == null) {
            createLoginLog(null, username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            saveLoginErrorIp();
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.USER_DISABLED);
            saveLoginErrorIp();
            saveUserLoginError(user.getId());
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }
        //检查用户登录错误次数，超过了 安全设置的用户允许尝试次数则锁定用户多长时间
        checkUserLoginErrorCount(user.getId(), securityConfig);
        //检查密码
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            saveLoginErrorIp();
            saveUserLoginError(user.getId());
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        //检查是否允许异地登录，如果不允许则退出之前的登录token
        final Object cacheToken = cacheService.getCacheObject(LOGIN_USER_TOKEN + ":" + user.getId());
        if (!securityConfig.isMultiLoginEnable() && cacheToken != null) {
            String beforeLoginToken = (String) cacheToken;
            logout(beforeLoginToken, LoginLogTypeEnum.LOGOUT_DELETE.getType());
        }
        //登录成功删除ip登录次数和登录错误次数缓存
        clearLoginErrorCache(user.getId());
        return user;
    }

    private AdminUserDO authenticate(AuthLoginReqVO reqVO) {
        AdminUserDO user = authenticate(reqVO.getUsername(), reqVO.getPassword());
        //开启了双因子认证则需要验证手机号和验证码，目前只作用于管理员用户，前台会员用户暂时不考虑双因子短信验证
        final CommonResult<GlobalConfigRespVO> globalConfigResp = globalConfigApi.getGlobalConfig();
        SecurityConfig securityConfig;
        if (globalConfigResp.isSuccess()) {
            securityConfig = globalConfigResp.getData().getSecurityConfig();
            if (securityConfig.isTwoFactor() && UserTypeEnum.ADMIN.getValue().equals(user.getUserType())) {
                // 校验验证码
                smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.ADMIN_MEMBER_LOGIN.getScene(), getClientIP()));
            }
        }
        return user;
    }

    @Override
    public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
        // 校验验证码
        validateCaptcha(reqVO);
        final String decryptPassword = SM2Util.decrypt(reqVO.getPassword(), jproProperties.getClientSm2PrivateKey());
        // 使用账号密码，进行登录
        reqVO.setPassword(decryptPassword);
        AdminUserDO user = authenticate(reqVO);


        // 如果 socialType 非空，说明需要绑定社交用户
        if (reqVO.getSocialType() != null) {
            socialUserService.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType(user).getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }
        // 创建 Token 令牌，记录登录日志
        final AuthLoginRespVO authLoginRespVO = createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);

        //登录成功则记录用户token 到redis key  login_user_token:{userid}
        saveUserTokenToRedis(user.getId(), authLoginRespVO.getAccessToken());
        authLoginRespVO.setDefSiteId(user.getDefSiteId());
        return authLoginRespVO;
    }

    @Override
    public MemberUserRespVo simpleLogin(SimpleAuthLoginReqVO reqVO) {
        // 使用账号密码，进行登录
        AdminUserDO user = authenticate(reqVO.getUsername(), SM2Util.decrypt(reqVO.getPassword(), jproProperties.getClientSm2PrivateKey()));
        // 创建 Token 令牌，记录登录日志
        final AuthLoginRespVO authLoginRespVO = createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
        //登录成功则记录用户token 到redis key  login_user_token:{userid}
        saveUserTokenToRedis(user.getId(), authLoginRespVO.getAccessToken());
        MemberUserRespVo memberUserRespVo = new MemberUserRespVo();
        final Long userId = authLoginRespVO.getUserId();
        final AdminUserDO adminUserDO = userService.getUser(userId);
        if (adminUserDO != null) {
            memberUserRespVo = MemberUserConvert.INSTANCE.convert(authLoginRespVO, adminUserDO);
            if (adminUserDO.getDeptId() != null) {
                memberUserRespVo.setDeptName(deptService.getDept(adminUserDO.getDeptId()).getName());
            }
        }
        return memberUserRespVo;
    }

    @Override
    public void sendSmsCode(AuthSmsSendReqVO reqVO) {
        // 登录场景，验证是否存在
        if (userService.getUserByMobile(reqVO.getMobile()) == null) {
            throw exception(AUTH_MOBILE_NOT_EXISTS);
        }
        // 发送验证码
        smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP())).checkError();
    }

    @Override
    public AuthLoginRespVO smsLogin(AuthSmsLoginReqVO reqVO) {
        // 校验验证码
        smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.ADMIN_MEMBER_LOGIN.getScene(), getClientIP())).getCheckedData();

        // 获得用户信息
        AdminUserDO user = userService.getUserByMobile(reqVO.getMobile());
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE);
    }

    private void createLoginLog(Long userId, String username,
                                LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult) {
        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logTypeEnum.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType(userService.getUser(userId)).getValue());
        reqDTO.setUsername(username);
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(ServletUtils.getClientIP());
        reqDTO.setResult(loginResult.getResult());
        loginLogService.createLoginLog(reqDTO);
        // 更新最后登录时间
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
            userService.updateUserLogin(userId, ServletUtils.getClientIP());
        }
    }

    @Override
    public AuthLoginRespVO socialLogin(AuthSocialLoginReqVO reqVO) {
        // 使用 code 授权码，进行登录。然后，获得到绑定的用户编号
        SocialUserRespDTO socialUser = socialUserService.getSocialUserByCode(UserTypeEnum.ADMIN.getValue(), reqVO.getType(),
                reqVO.getCode(), reqVO.getState());
        if (socialUser == null || socialUser.getUserId() == null) {
            throw exception(AUTH_THIRD_LOGIN_NOT_BIND);
        }

        // 获得用户
        AdminUserDO user = userService.getUser(socialUser.getUserId());
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL);
    }

    @VisibleForTesting
    void validateCaptcha(AuthLoginReqVO reqVO) {
        // 如果验证码关闭，则不进行校验
        if (!captchaEnable) {
            return;
        }
        // 校验验证码
        ValidationUtils.validate(validator, reqVO, AuthLoginReqVO.CodeEnableGroup.class);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaVerification(reqVO.getCaptchaVerification());
        ResponseModel response = captchaService.verification(captchaVO);
        // 验证不通过
        if (!response.isSuccess()) {
            // 创建登录失败日志（验证码不正确)
            createLoginLog(null, reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.CAPTCHA_CODE_ERROR);
            throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR, response.getRepMsg());
        }
    }

    private AuthLoginRespVO createTokenAfterLoginSuccess(Long userId, String username, LoginLogTypeEnum logType) {
        // 插入登陆日志
        createLoginLog(userId, username, logType, LoginResultEnum.SUCCESS);
        // 创建访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(userId, getUserType(userService.getUser(userId)).getValue(),
                OAuth2ClientConstants.CLIENT_ID_DEFAULT, null);
        // 构建返回结果
        return AuthConvert.INSTANCE.convert(accessTokenDO);
    }

    @Override
    public AuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return AuthConvert.INSTANCE.convert(accessTokenDO);
    }

    @Override
    public MemberAuthLoginRespVO refreshTokenPortal(String refreshToken) {
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return AuthConvert.INSTANCE.convertForMember(accessTokenDO);
    }

    @Override
    public void logout(String token, Integer logType) {
        // 删除访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.removeAccessToken(token);
        if (accessTokenDO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenDO.getUserId(), accessTokenDO.getUserType(), logType);
    }

    private void createLogoutLog(Long userId, Integer userType, Integer logType) {
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType);
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(userType);
        if (ObjectUtil.equal(getUserType(userService.getUser(userId)).getValue(), userType)) {
            reqDTO.setUsername(getUsername(userId));
        } else {
            reqDTO.setUsername(memberService.getMemberUserMobile(userId));
        }
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(ServletUtils.getClientIP());
        reqDTO.setResult(LoginResultEnum.SUCCESS.getResult());
        loginLogService.createLoginLog(reqDTO);
    }

    private String getUsername(Long userId) {
        if (userId == null) {
            return null;
        }
        AdminUserDO user = userService.getUser(userId);
        return user != null ? user.getUsername() : null;
    }

//    private UserTypeEnum getUserType() {
//        return UserTypeEnum.ADMIN;
//    }

    private UserTypeEnum getUserType(AdminUserDO userDO) {
//        HttpServletRequest request = RequestUtils.getHttpServletRequest();
        /**后台管理用户去访问前台认定位前台用户*/
//        if(request!=null){
//            if (request.getRequestURI().startsWith(webProperties.getAppApi().getPrefix())) {
//                return UserTypeEnum.MEMBER;
//            }
//            if (request.getRequestURI().startsWith(webProperties.getFrontApi().getPrefix())) {
//                return UserTypeEnum.MEMBER;
//            }
//            if (request.getRequestURI().startsWith(FRONT_LOGIN_API)) {
//                return UserTypeEnum.MEMBER;
//            }
//        }
        if (UserTypeEnum.MEMBER.getValue().equals(userDO.getUserType())) {
            return UserTypeEnum.MEMBER;
        }
        return UserTypeEnum.ADMIN;
    }

    private void saveLoginErrorIp() {
        final String ip = RequestUtils.getRemoteAddr(RequestUtils.getHttpServletRequest());
        String cacheKey = LOGIN_ERROR_IP + ":" + ip;
        Integer loginCountByIp = 1;
        final Object cacheObject = cacheService.getCacheObject(cacheKey);
        if (cacheObject != null) {
            Integer errorCount = (Integer) cacheObject;
            loginCountByIp = errorCount + 1;
        }
        //2小时内禁用ip登录
        cacheService.setCacheObject(cacheKey, loginCountByIp, 2L, TimeUnit.HOURS);
    }

    private void clearLoginErrorCache(Long userId) {
        final String ip = RequestUtils.getRemoteAddr(RequestUtils.getHttpServletRequest());
        String cacheKey = LOGIN_ERROR_IP + ":" + ip;
        cacheService.deleteObject(cacheKey);
        String cacheKey2 = LOGIN_ERROR_USER + ":" + userId;
        cacheService.deleteObject(cacheKey2);
    }


    private void checkIpForbidden(SecurityConfig securityConfig) {
        final int ipMaxAttempts = securityConfig.getIpMaxAttempts();
        if (ipMaxAttempts > 0) {
            final String ip = RequestUtils.getRemoteAddr(RequestUtils.getHttpServletRequest());
            String cacheKey = LOGIN_ERROR_IP + ":" + ip;
            final Object cacheObject = cacheService.getCacheObject(cacheKey);
            if (cacheObject != null) {
                Integer errorCount = (Integer) cacheObject;
                if (errorCount > ipMaxAttempts) {
                    log.error("登录失败，ip暂时不允许登录,{} 错误次数已达到 {} 最大限制是 {}", ip, errorCount, ipMaxAttempts);
                    throw exception(AUTH_LOGIN_IP_FORBIDDEN);
                }
            }
        }
    }

    private void checkUserLoginErrorCount(Long userId, SecurityConfig securityConfig) {
        final int userMaxAttempts = securityConfig.getUserMaxAttempts();
        String cacheKey = LOGIN_ERROR_USER + ":" + userId;
        final Object cacheObject = cacheService.getCacheObject(cacheKey);
        if (userMaxAttempts > 0 && cacheObject != null) {
            Integer errorCount = (Integer) cacheObject;
            if (errorCount > userMaxAttempts) {
                log.error("超过用户允许尝试次数限制，错误次数已达到 {} 最大限制是 {}", errorCount, userMaxAttempts);
                //触发子线程去禁用该账户并执行定时任务去定时启用用户
                threadPoolTaskExecutor.execute(() -> {
                    userService.lockUser(new UserLockReqVO(userId, "超过用户允许尝试次数限制"));
                    //定时任务 后续解锁
                    jobService.createEnableUserJob(userId, DateUtil.offset(DateUtil.date(), DateField.MINUTE, securityConfig.getUserLockMinutes()));
                });
                throw exception(AUTH_LOGIN_USER_MAX_FORBIDDEN);
            }
        }
    }

    private void saveUserLoginError(Long userId) {
        String cacheKey = LOGIN_ERROR_USER + ":" + userId;
        Integer loginCountByUser = 1;
        final Object cacheObject = cacheService.getCacheObject(cacheKey);
        if (cacheObject != null) {
            Integer errorCount = (Integer) cacheObject;
            loginCountByUser = errorCount + 1;
        }
        //1天内禁用多长时间的限制，用户允许尝试次数在1天内
        cacheService.setCacheObject(cacheKey, loginCountByUser, 1L, TimeUnit.DAYS);
    }

    private void saveUserTokenToRedis(Long userId, String accessToken) {
        String cacheKey = LOGIN_USER_TOKEN + ":" + userId;
        cacheService.setCacheObject(cacheKey, accessToken, 1L, TimeUnit.DAYS);
    }

    /**
     * @Description: 判断ip是否在ip白名单内
     */
    public Boolean ipIsAllowd(String ip, AdminIpConfig adminIpConfig) {
        if (EnumIntCommonStatus.CLOSE.getStatus().equals(adminIpConfig.getLimitOpen())) {
            return true;
        }
        final List<String> ips = adminIpConfig.getIps();
        if (CollUtil.isNotEmpty(ips) && ips.contains(ip)) {
            return true;
        }
        Long ipLong = -1L;
        try {
            //0:0:0:0:0:0:0:1 等识别不到的IP则不拦截
            ipLong = Ipv4Util.ipv4ToLong(ip);
        } catch (Exception e) {
            return true;
        }
        final List<IpRangeVO> ipRanges = adminIpConfig.getIpRanges();
        for (IpRangeVO ipRange : ipRanges) {
            final boolean inner = isInner(ipLong, Ipv4Util.ipv4ToLong(ipRange.getFrom()), Ipv4Util.ipv4ToLong(ipRange.getTo()));
            if (inner) {
                return true;
            }
        }
        return false;
    }

    /**
     * 指定IP的long是否在指定范围内
     *
     * @param userIp 用户IP
     * @param begin  开始IP
     * @param end    结束IP
     * @return 是否在范围内
     */
    private static boolean isInner(long userIp, long begin, long end) {
        return (userIp >= begin) && (userIp <= end);
    }


}
